package shuishijie.suishijie;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import static android.R.attr.action;
import com.bumptech.glide.Glide;
import com.mob.tools.utils.UIHandler;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.UiError;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;
import okhttp3.internal.platform.Platform;
import shuishijie.suishijie.fragment.OrderPayFragment;
import shuishijie.suishijie.util.WechartUtil;

import static cn.sharesdk.wechat.friends.Wechat.*;

public class WebViewActivity extends BaseActivity implements View.OnClickListener,  Handler.Callback ,PlatformActionListener {
    private static final String EXTRA_PERMISSIONS =
            "me.chunyu.clwang.permission.extra_permission"; // 权限参数
    private static final String PACKAGE_URL_SCHEME = "package:"; // 方案
    public static final int PERMISSIONS_GRANTED = 0; // 权限授权
    public static final int PERMISSIONS_DENIED = 1; // 权限拒绝
    private static final int PERMISSION_REQUEST_CODE = 0; // 系统权限管理页面的参数
	private WebView webView;
	private LinearLayout ll_progress;
    private TextView tv_title;
    private LinearLayout title;
    private final static int SCANNIN_GREQUEST_CODE = 1;
    public static final int CAMERA_REQUEST_CODE = 2;
    public static final int MAP_MARKER = 3;
    String str;
    private Uri uri;
    private String Type;
    String url;
    private String AGENT_FARMER_ID;
   // private DocementsModel docementsModel;
    //图片类型（文件类型，1：手持身份证，2：身份证正面，3，身份证反面，4：房产证，5：驾驶证）
    private String fileType;
    private String path;
    private Bitmap bp;
    private cn.sharesdk.framework.Platform.ShareParams sp;
    private cn.sharesdk.framework.Platform plat;
    private String PicName;
    private String orderid;
    private String mobile;
    private String token;
    private String user_id;
    private int THUMB_SIZE = 32;
    private String card_id;
    private String way;
    private String link;
    private String type;
    private String urlnew;
    private IUiListener uiListener = new IUiListener() {
        @Override
        public void onComplete(Object o) {
            Toast.makeText(WebViewActivity.this, "分享成功", Toast.LENGTH_SHORT).show();
            //AlertUtil.t(InviteFriendActivity.this, "分享成功");
        }



        @Override
        public void onError(UiError uiError) {
            Toast.makeText(WebViewActivity.this, "分享失败", Toast.LENGTH_SHORT).show();
            //AlertUtil.t(InviteFriendActivity.this, "分享失败");
        }

        @Override
        public void onCancel() {
            Toast.makeText(WebViewActivity.this, "取消分享", Toast.LENGTH_SHORT).show();
           // AlertUtil.t(InviteFriendActivity.this, "取消分享");
        }
    };

    private IWXAPI api;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.webview);
        urlnew=getIntent().getStringExtra("url");
        type=getIntent().getStringExtra("type");
        api = WXAPIFactory.createWXAPI(this, WechartUtil.APPID, true);
        api.registerApp(WechartUtil.APPID);
       // sp = new Platform.ShareParams();
        webView = (WebView) findViewById(R.id.webView);


       // url="http://192.168.1.134:8080/app/#/main/gvgMall";
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true); // 支持通过JS打开新窗口
        settings.setAllowFileAccess(true);
        settings.setSupportMultipleWindows(true);
        settings.setSupportZoom(true);
        // settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //优先加载缓存
        // settings.setAppCacheEnabled(true);
        settings.setDomStorageEnabled(true); // 必须进行这个设置
        // settings.setAppCachePath(this.getCacheDir().getAbsolutePath());
        // settings.setDatabaseEnabled(true);
        // settings.setDatabasePath(this.getCacheDir().getAbsolutePath());
        settings.setBuiltInZoomControls(false); // 不支持缩放
        // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
        // {
        // settings.setDisplayZoomControls(false); // 不显示缩放按钮
        // }
        // settings.setUseWideViewPort(true); // 无限缩放
        settings.setLoadWithOverviewMode(true); // 初始加载时，是web页面自适应屏幕
        webView.addJavascriptInterface(new JavaScriptClass(), "android");
        webView.getSettings().setBlockNetworkImage(false);
        webView.getSettings().setJavaScriptEnabled(true);
        int screenDensity = getResources().getDisplayMetrics().densityDpi;
        WebSettings.ZoomDensity zoomDensity = WebSettings.ZoomDensity.MEDIUM;
        switch (screenDensity) {
            case DisplayMetrics.DENSITY_LOW:
                zoomDensity = WebSettings.ZoomDensity.CLOSE;
                break;
            case DisplayMetrics.DENSITY_MEDIUM:
                zoomDensity = WebSettings.ZoomDensity.MEDIUM;
                break;
            case DisplayMetrics.DENSITY_HIGH:
                zoomDensity = WebSettings.ZoomDensity.FAR;
                break;
        }
        settings.setDefaultZoom(zoomDensity);
        webView.requestFocus();
        webView.requestFocusFromTouch();
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message,
                                     JsResult result) {
                return super.onJsAlert(view, url, message, result);
            }
        });

        webView.setWebViewClient(new WebViewClient() {

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //view.loadUrl(url);
//                if (url.contains("https://offline.gvg666.com/dist/index.html#/main/gvgMall")) {
//                    Intent intent =new Intent(WebViewActivity.this,PayActivity.class);
//                    startActivity(intent);
//                    return true;
//
//                }
//                if(url.contains("user/log.html"))
//                {
//
//                    return true;
//                }
//                if(url.contains("user/personalCenter.html"))
//                {
//
//                    return true;
//                }
                return false;
            }

            @Override
            public void doUpdateVisitedHistory(WebView view, String url,
                                               boolean isReload) {
                super.doUpdateVisitedHistory(view, url, isReload);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);


            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);

            }
        });
        if(type!=null)
        {
            webView.loadUrl(urlnew);
        }else {
            url="https://offline.gvg666.com/dist/index.html#/main/gvgMall";
            webView.loadUrl(url);
        }
        URL url1 = null;
        try {
            url1 = new URL(null);
            HttpURLConnection conn = (HttpURLConnection) url1.openConnection();

            conn.setRequestMethod("GET");

            conn.connect();
            if(conn.getResponseCode() == HttpURLConnection.HTTP_OK) {

                Map<String, List<String>> headFields = conn.getHeaderFields();

                List<String> cookieList = headFields.get("Set-Cookie");

                CookieManager cookieManager = CookieManager.getInstance();

                for(String cookie: cookieList) {

                    cookieManager.setCookie(String.valueOf(url), cookie);

                }

            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //然后通过CookieManager的setCookie方法把url跟cookie绑定下就好了。




    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    @Override
    public void onClick(View v) {

    }

//    @Override
//    public boolean handleMessage(Message msg) {
//        return false;
//    }



    @Override
    public void onComplete(cn.sharesdk.framework.Platform platform, int i, HashMap<String, Object> hashMap) {
        Message msg = new Message();
        msg.arg1 = 1;
        msg.arg2 = action;
        msg.obj = platform;
        UIHandler.sendMessage(msg, this);
    }

    @Override
    public void onError(cn.sharesdk.framework.Platform platform, int i, Throwable throwable) {
        Message msg = new Message();
        msg.arg1 = 2;
       msg.arg2 = action;
        msg.obj = throwable;
        UIHandler.sendMessage(msg, this);
    }

    @Override
    public void onCancel(cn.sharesdk.framework.Platform platform, int i) {
        Message msg = new Message();
        msg.arg1 = 3;
        msg.arg2 = action;
        msg.obj = platform;
        UIHandler.sendMessage(msg, this);
    }
    public void friendCircle() {
        //朋友圈
        if (!api.isWXAppInstalled()) {
            Toast.makeText(WebViewActivity.this, "您还未安装微信客户端", Toast.LENGTH_SHORT).show();
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
//                    Bitmap bmp = null;
//                    try {
//                        bmp = Glide.with(WebViewActivity.this)
//                                .load("mobile/images/btcf.png")
//                                .asBitmap()
//                                .centerCrop()
//                                .into(THUMB_SIZE, THUMB_SIZE)
//                                .get();
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                        Log.e("jin", "InterruptedException: ");
//
//                    } catch (ExecutionException e) {
//                        e.printStackTrace();
//                        Log.e("jin", "ExecutionException: ");
//                    } finally {
                Message msg = new Message();
                msg.arg1 = 5;
                msg.arg2 = action;
                //msg.obj = bmp;
                UIHandler.sendMessage(msg, WebViewActivity.this);
            }
           // }
        }).start();
    }
    //交互方法
    class JavaScriptClass {
        @JavascriptInterface
        public void  onBtnClick(String l1,String l2,String l3,String
                l4)
        {
            Intent intent =new Intent(WebViewActivity.this,PayActivity.class);
            intent.putExtra("orderid",l1);
            intent.putExtra("mobile",l2);
            intent.putExtra("token",l3);
            intent.putExtra("user_id",l4);
            startActivity(intent);
            Log.e("KKK",l1+""+l2+""+l3+""+l4);
            orderid=l1;
            mobile=l2;
            token=l3;
            user_id=l4;
          //  Toast.makeText(WebViewActivity.this, token, Toast.LENGTH_SHORT).show();
        }
        @JavascriptInterface
        public void share(String cardid,String userid,String way)
        {
            link="https://offline.gvg666.com/dist/index.html#/load/download?cardId="+cardid+"&userId="+userid;

            if(way.equals("0"))
            {
                weChat();
            }else
            {
                friendCircle();
            }
        }
    }
    @Override
    public boolean handleMessage(Message message) {
        String text = "";
        switch (message.arg1) {
            case 1: {
                // 成功
                Platform plat = (Platform) message.obj;
                // text = plat.getName() + "share completed ";
                text = "分享成功 ";
            }
            Toast.makeText(this, "分享成功", Toast.LENGTH_SHORT).show();
            break;
            case 2: {
                // 失败
                if ("WechatClientNotExistException".equals(message.obj.getClass().getSimpleName())) {
                    //text = this.getString(R.string.wechat_client_inavailable);
                } else if ("WechatTimelineNotSupportedException".equals(message.obj.getClass().getSimpleName())) {
                   // text = this.getString(R.string.wechat_client_inavailable);
                } else {
                    //text = this.getString(R.string.share_failed);
                }
            }
            Toast.makeText(this, "分享失败", Toast.LENGTH_SHORT).show();
            break;
            case 3: {
                // 取消
                Platform plat = (Platform) message.obj;
                // text = plat.getName() + " canceled ";
                text = "取消分享 ";
            }
            Toast.makeText(this, "取消分享", Toast.LENGTH_SHORT).show();
            break;
            case 4:
                Bitmap bmp = (Bitmap) message.obj;
                WXWebpageObject webpageObject = new WXWebpageObject();
                webpageObject.webpageUrl =link;
                WXMediaMessage msg = new WXMediaMessage(webpageObject);
                msg.title = "世界村水世界";
                msg.description = "邀请您加入水世界平台，乐享安全、高收益的投资回报！";
                msg.setThumbImage(bp);
                if (bmp != null) {
                    bmp.recycle();
                }
                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.message = msg;
                req.transaction = "webpage";
                req.scene = SendMessageToWX.Req.WXSceneSession;
                api.sendReq(req);

                break;
            case 5:
                //Bitmap bmp1 = (Bitmap) message.obj;
                Resources res = getResources();
                bp = BitmapFactory.decodeResource(res, R.mipmap.logo);
                WXWebpageObject webpageObject1 = new WXWebpageObject();
                webpageObject1.webpageUrl =link;
                WXMediaMessage msg1 = new WXMediaMessage(webpageObject1);
                msg1.title = "世界村水世界";
                msg1.description = "邀请您加入水世界平台，乐享安全、高收益的投资回报！";
                msg1.setThumbImage(bp);
                if (bp != null) {
                    bp.recycle();
                }
                SendMessageToWX.Req req1 = new SendMessageToWX.Req();
                req1.message = msg1;
                req1.transaction = "webpage";
                req1.scene = SendMessageToWX.Req.WXSceneTimeline;
                api.sendReq(req1);

                break;
            default:
                break;

        }

        //        AlertUtil.t(this, text);
        return false;
    }
    public void weChat() {
        //微信
        if (!api.isWXAppInstalled()) {
            Toast.makeText(this, "您还未安装微信客户端", Toast.LENGTH_SHORT).show();
            //AlertUtil.t(InviteFriendActivity.this, "您还未安装微信客户端", Toast.LENGTH_SHORT);
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
//                Bitmap bmp = null;
//                try {
//                    bmp = Glide.with(getApplicationContext())
//                            .load("https://image.baidu.com/search/detail?ct=503316480&z=0&ipn=d&word=%E6%B7%98%E5%AE%9D&step_word=&hs=0&pn=1&spn=0&di=61040852510&pi=0&rn=1&tn=baiduimagedetail&is=0%2C0&istype=0&ie=utf-8&oe=utf-8&in=&cl=2&lm=-1&st=undefined&cs=2111509796%2C1998071314&os=3568410211%2C1864346178&simid=4213041868%2C919940859&adpicid=0&lpn=0&ln=1978&fr=&fmq=1514044300007_R&fm=&ic=undefined&s=undefined&se=&sme=&tab=0&width=undefined&height=undefined&face=undefined&ist=&jit=&cg=&bdtype=0&oriquery=&objurl=http%3A%2F%2Fimg.weixinyidu.com%2F151228%2F5767343c.jpg&fromurl=ippr_z2C%24qAzdH3FAzdH3Fooo_z%26e3Bojtxtgyt17_z%26e3Bv54AzdH3Fg_d0c8a0l&gsm=0&rpstart=0&rpnum=0")
//                            .asBitmap()
//                            .centerCrop()
//                            .into(THUMB_SIZE, THUMB_SIZE)
//                            .get();
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                    Log.e("jin", "InterruptedException: ");
//
//                } catch (ExecutionException e) {
//                    e.printStackTrace();
//                    Log.e("jin", "ExecutionException: ");
//                } finally {
                    Message msg = new Message();
                    msg.arg1 = 4;
                     msg.arg2 = action;
                   // msg.obj = bmp;
                    UIHandler.sendMessage(msg, WebViewActivity.this);
                }
            //}
        }).start();
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            webView.goBack();// 返回前一个页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }





}
